package ru.rs.framework.objects;

import ru.rs.framework.interfaces.Game;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class RenderView extends SurfaceView implements Runnable {

	private Bitmap frame;
	private volatile boolean running;
	private Game game;
	private SurfaceHolder holder;

	private Thread renderThread = null;

	public RenderView(AbstractActivity context, Bitmap fr) {
		super(context);
		frame = fr;
		game = context;
		holder = getHolder();
	}

	@Override
	public void run() {
		Rect rect = new Rect();
		long start = System.nanoTime();
		while (running) {

			if (!holder.getSurface().isValid()) {
				continue;
			}

			float delta = (System.nanoTime() - start) / 1000000000.0f;
			start = System.nanoTime();

			Screen screen = game.getCurrentScreen();
			screen.update(delta);
			screen.render(delta);
			Canvas canvas = holder.lockCanvas();
			canvas.getClipBounds(rect);
			canvas.drawBitmap(frame, null, rect, null);
			holder.unlockCanvasAndPost(canvas);
		}
	}

	// //////////////////////////////////////////////////////////////////////
	public void pause() {
		running = false;
		while (true) {
			try {
				if (renderThread != null) {
					renderThread.join();
				}
				break;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void resume() {
		running = true;
		renderThread = new Thread(this);
		renderThread.start();
	}
}
